package com.xlh.openai.listener;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.db.sql.Order;
import com.xlh.openai.entity.OrderEntity;
import com.xlh.openai.service.OrderService;
import com.xlh.openai.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.DelayQueue;

/**
 * @author chufangzheng
 */
@Component
@Slf4j
public class OrderListener implements ApplicationListener<ContextRefreshedEvent> {

    private static DelayQueue<OrderDelay> delayQueue = new DelayQueue();

    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Autowired
    private OrderService orderService;

    @Autowired
    private ProductService productService;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {

        // 1. 查询所有未过期的订单 放在队列中
        List<OrderEntity>  notExpireOrders = orderService.listNotExpireOrders();
        if( CollectionUtil.isNotEmpty(notExpireOrders) ){
            notExpireOrders.stream().forEach(order -> addQueue(order));
        }
        new Thread(()->{
            while(true){
                try {
                    OrderDelay take = delayQueue.take();
                    threadPoolTaskExecutor.execute(take);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public void addQueue( OrderEntity orderEntity){

        OrderDelay orderDelay = new OrderDelay();
        orderDelay.setSecond((orderEntity.getTimeExpire().getTime()/1000));
        orderDelay.setOrderId(orderEntity.getId());
        orderDelay.setOrderService(orderService);
        orderDelay.setProductService(productService);
        // 添加之前的信息
        delayQueue.add(orderDelay);
        Arrays.stream(delayQueue.stream().toArray()).forEach(productStock->{
            log.info( "队列信息：" + productStock.toString());
        });
    }

}
